package net.wicp.tams.duckula.server.service;

import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.JmxUtil;
import net.wicp.tams.commons.apiext.StringUtil;

/***
 * 给客户端提供工具方法
 * 
 * @author zhoujunhui
 *
 */
@Slf4j
public abstract class MBeanUtil {

	public static JMXConnector getConn(String taskId) {
		JMXConnector conn = JmxUtil.connect(StringUtil.buildPort(taskId));
		return conn;
	}

	public static ObjectName getBinlogControlMBean(JMXConnector conn) {
		ObjectName bean = JmxUtil.queryMBean(conn, "Commons:name=BinlogControl");
		return bean;
	}

	/***
	 * 停止服务
	 * 
	 * @param conn
	 * @return
	 */
	public static Result stopTask(JMXConnector conn) {
		ObjectName bean = MBeanUtil.getBinlogControlMBean(conn);
		try {
			conn.getMBeanServerConnection().invoke(bean, "stop", null, null);
			return Result.getSuc();
		} catch (Exception e) {
			return Result.getError(e.getMessage());
		}
	}

	public static Result putSync(JMXConnector conn, int sync) {
		ObjectName bean = MBeanUtil.getBinlogControlMBean(conn);
		try {
			conn.getMBeanServerConnection().invoke(bean, "putSync", new Object[sync], null);
			return Result.getSuc();
		} catch (Exception e) {
			return Result.getError(e.getMessage());
		}
	}

	public static Boolean findSync(JMXConnector conn) {
		ObjectName bean = MBeanUtil.getBinlogControlMBean(conn);
		try {
			Object retobj = conn.getMBeanServerConnection().invoke(bean, "findSync", null, null);
			return Boolean.valueOf(String.valueOf(retobj));
		} catch (Exception e) {
			log.error("查找是否同步状态错误", e);
			return null;
		}
	}

}
